package com.my.json.sensitive.config;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.my.json.sensitive.annotation.SensitiveField;
import com.my.json.sensitive.enums.SensitiveType;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * 专门用于FastJsonConfiguration的配置
 */
public class SensitiveInfoFastJsonFilter implements ValueFilter {
    private static final CompositeSensitiveHandler handler = new CompositeSensitiveHandler();

    @Override
    public Object process(Object object, String name, Object value) {
        if (value instanceof String) {
            // 获取字段上的SensitiveField注解
            SensitiveField annotation = getSensitiveFieldAnnotation(object.getClass(), name);
            if (annotation != null && value != null) {
                SensitiveType type = annotation.type();
                return !SensitiveType.NULL.equals(type) ?  // 非NULL类型使用专用处理器
                        handler.sensitive((String) value, type) :
                        split((String) value, annotation.prefix(), annotation.suffix(), annotation.split()); // NULL类型使用默认split方法
            }
        }
        return value;
    }

    private SensitiveField getSensitiveFieldAnnotation(Class<?> clazz, String fieldName) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            return field.getAnnotation(SensitiveField.class);
        } catch (NoSuchFieldException e) {
            // 递归检查父类
            if (clazz.getSuperclass() != Object.class) {
                return getSensitiveFieldAnnotation(clazz.getSuperclass(), fieldName);
            }
            return null;
        }
    }
    private String split(String text, int prefix, int suffix, int split) {
        if (text == null || text.length() <= prefix + suffix) {
            return text;
        }
        return text.substring(0, prefix) +
            StringUtils.repeat("*", split) +  // Use Apache Commons StringUtils
            text.substring(text.length() - suffix);
    }
}